package com.example.ssrbac.service.impl;

import com.example.ssrbac.dto.PermissionDTO;
import com.example.ssrbac.entity.Permission;
import com.example.ssrbac.repository.PermissionRepository;
import com.example.ssrbac.service.PermissionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityNotFoundException;

@Service
public class PermissionServiceImpl implements PermissionService {
    private static final Logger logger = LoggerFactory.getLogger(PermissionServiceImpl.class);

    @Autowired
    private PermissionRepository permissionRepository;

    @Override
    @Transactional
    public PermissionDTO createPermission(PermissionDTO permissionDTO) {
        logger.info("Creating new permission with name: {}", permissionDTO.getName());
        if (permissionRepository.existsByName(permissionDTO.getName())) {
            logger.error("Permission name already exists: {}", permissionDTO.getName());
            throw new IllegalArgumentException("权限名称已存在");
        }
        if (permissionRepository.findByResourceAndAction(permissionDTO.getResource(), permissionDTO.getAction())
                .isPresent()) {
            logger.error("Permission with resource {} and action {} already exists", 
                permissionDTO.getResource(), permissionDTO.getAction());
            throw new IllegalArgumentException("该资源路径和操作类型的组合已存在");
        }

        Permission permission = new Permission();
        BeanUtils.copyProperties(permissionDTO, permission);

        Permission savedPermission = permissionRepository.save(permission);
        logger.info("Permission created successfully with ID: {}", savedPermission.getId());
        BeanUtils.copyProperties(savedPermission, permissionDTO);
        return permissionDTO;
    }

    @Override
    @Transactional
    public PermissionDTO updatePermission(Long id, PermissionDTO permissionDTO) {
        logger.info("Updating permission with ID: {}", id);
        Permission permission = permissionRepository.findById(id)
                .orElseThrow(() -> {
                    logger.error("Permission not found: {}", id);
                    return new EntityNotFoundException("权限不存在");
                });

        if (!permission.getName().equals(permissionDTO.getName()) && 
            permissionRepository.existsByName(permissionDTO.getName())) {
            logger.error("Permission name already exists: {}", permissionDTO.getName());
            throw new IllegalArgumentException("权限名称已存在");
        }
        if ((!permission.getResource().equals(permissionDTO.getResource()) || 
             !permission.getAction().equals(permissionDTO.getAction())) &&
            permissionRepository.findByResourceAndAction(permissionDTO.getResource(), permissionDTO.getAction())
                .isPresent()) {
            logger.error("Permission with resource {} and action {} already exists", 
                permissionDTO.getResource(), permissionDTO.getAction());
            throw new IllegalArgumentException("该资源路径和操作类型的组合已存在");
        }

        BeanUtils.copyProperties(permissionDTO, permission);

        Permission updatedPermission = permissionRepository.save(permission);
        logger.info("Permission updated successfully: {}", id);
        BeanUtils.copyProperties(updatedPermission, permissionDTO);
        return permissionDTO;
    }

    @Override
    @Transactional
    public void deletePermission(Long id) {
        logger.info("Deleting permission with ID: {}", id);
        if (!permissionRepository.existsById(id)) {
            logger.error("Permission not found: {}", id);
            throw new EntityNotFoundException("权限不存在");
        }
        permissionRepository.deleteById(id);
        logger.info("Permission deleted successfully: {}", id);
    }

    @Override
    public PermissionDTO getPermissionById(Long id) {
        logger.debug("Fetching permission by ID: {}", id);
        Permission permission = permissionRepository.findById(id)
                .orElseThrow(() -> {
                    logger.error("Permission not found: {}", id);
                    return new EntityNotFoundException("权限不存在");
                });
        PermissionDTO permissionDTO = new PermissionDTO();
        BeanUtils.copyProperties(permission, permissionDTO);
        return permissionDTO;
    }

    @Override
    public Page<PermissionDTO> getAllPermissions(Pageable pageable) {
        logger.debug("Fetching all permissions with pagination: {}", pageable);
        return permissionRepository.findAll(pageable)
                .map(permission -> {
                    PermissionDTO permissionDTO = new PermissionDTO();
                    BeanUtils.copyProperties(permission, permissionDTO);
                    return permissionDTO;
                });
    }
} 